/**
 * Created by Administrator on 2017/7/18.
 */

var systemConfig = require('../../../config/systemConfig.json');
// 玩家管理器
function RankManager() {
    this._lastWeekPlayRound = {
        _id: "rankWeekPlayRound",
        week: (new Date()).getWeeks(),
        ranks: []
    };
    this._lastWeekPlayRoundUsers = {};

    this._curWeekPlayRoundUsers = {};
    this._curWeekPlayRound = [];
}

RankManager.prototype = {
    init: function (callback) {
        DB.world.findOne({ _id: "rankWeekPlayRound" }, {}, function (err, doc) {
            if (doc) {
                this._lastWeekPlayRound = doc;
                this._buildLastWeekPlayRoundUsers();
            }
            callback && callback();
        }.bind(this));
    },

    update: function (callback) {
        this._updateWeekPlayRound(callback);
    },

    _updateWeekPlayRound: function (callback) {
        var users = [];

        var weekTime = (new Date()).zeroWeek();
        var condition = {
            'dayVars.day': { '$gte': weekTime.getDays() },
            'weekVars.playRound': { '$gt': systemConfig["RankManage"]["setMinLevel"] }
        };
        var cursor = DB.user.find(condition, { 'weekVars.playRound': 1 });
        cursor.each(function (err, item) {
            if (err || !item) {
                this._doUpdateWeekPlayRound(weekTime, users, callback); return;
            }

            users.push({ uid: item._id, value: item.weekVars.playRound });

            if (cursor.isClosed()) {
                this._doUpdateWeekPlayRound(weekTime, users, callback);
            }
        }.bind(this));
    },

    _doUpdateWeekPlayRound: function (weekTime, users, callback) {
        users.sort(function (a, b) {
            return b.value - a.value;
        });

        var rankUidArray = [];
        var rankUsers = {};

        for (var i = 0, m = Math.min(users.length, systemConfig["RankManage"]["setGetDataNums"]); i < m; ++i) {
            var user = users[i];
            user.rank = i + 1;
            rankUsers[user.uid] = user;
            rankUidArray.push(user.uid);
        }

        var cursor = DB.user.find({ '_id': { '$in': rankUidArray } }, { 'info': 1 }).toArray(function (err, items) {
            if (items && !err) {
                items.forEach(function (item) {
                    var user = rankUsers[item._id];
                    if (user) {
                        user.name = item.info.name;
                        user.headpic = item.info.headpic;
                        user.sex = item.info.sex;
                    }
                });
            }
            var playRound = rankUidArray.map(function (v) {
                if (rankUsers[v]) {
                    return rankUsers[v]
                }else{
                    return  0;
                }
            }).filter(function(v){
                return v != 0;
            });

            var week = weekTime.getWeeks();
            if (week != this._lastWeekPlayRound.week) {
                this._lastWeekPlayRound.week = week;
                this._lastWeekPlayRound.ranks = clone(this._curWeekPlayRound);
                this._buildLastWeekPlayRoundUsers();
                DB.world.save(this._lastWeekPlayRound);
                logger.debug("rank WeekPlayRound week=%d ranks=%j", week, this._lastWeekPlayRound.ranks);
            }

            this._curWeekPlayRoundUsers = rankUsers;
            this._curWeekPlayRound = playRound;

            callback && callback();
        }.bind(this));
    },

    _buildLastWeekPlayRoundUsers: function() {
        var ranks = this._lastWeekPlayRound.ranks;
        var rankUsers = {};
        if(ranks){
            var keys = Object.keys(ranks);
            ranks = keys.map(function(v){
                return ranks[v];
            })
        }
        
        ranks.forEach(function(user) {
            rankUsers[user.uid] = user;
        });
        this._lastWeekPlayRoundUsers = rankUsers;
    },

    getCurWeekPlayRoundRanks: function () {
        return this._curWeekPlayRound;
    },

    getCurWeekPlayRoundRank: function(uid) {
        var user = this._curWeekPlayRoundUsers[uid];
        return (user) ? user.rank : 0;
    },

    getLastWeekPlayRoundRanks: function() {
        return this._lastWeekPlayRound;
    },

    getLastWeekPlayRoundRank: function(uid) {
        var user = this._lastWeekPlayRoundUsers[uid];
        return (user) ? user.rank : 0;
    }
}


exports.RankManager = RankManager;